package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * OrderTradeStrategy策略接口实现类对象的管理类型
 */
@Component
public class OrderTradeStrategyContext implements ApplicationContextAware {

    /**
     * 定义一个Map管理OrderTradeStrategy策略接口实现类对象
     */
    private static final ConcurrentHashMap<String , OrderTradeStrategy> ORDER_TRADE_STRATEGY_MAP = new ConcurrentHashMap<>() ;

    // 根据付款项目的类型从ORDER_TRADE_STRATEGY_MAP中获取对应的策略实现类的对象
    public static OrderTradeStrategy getOrderTradeStrategy(String itemType) {
        return ORDER_TRADE_STRATEGY_MAP.get(itemType) ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        // 从Spring容器中获取OrderTradeStrategy策略接口实现类对象
        Map<String, OrderTradeStrategy> beansOfType = applicationContext.getBeansOfType(OrderTradeStrategy.class);      // map的键就是策略实现类的对象名称，值就是实现类对象
        beansOfType.values().forEach(orderTradeStrategy -> {
            String itemType = orderTradeStrategy.getItemType();     // 获取指定的实现类对象所对应的付款项目的类型
            ORDER_TRADE_STRATEGY_MAP.put(itemType , orderTradeStrategy) ;
        });

    }
}
